package lab6.systemCustom;

import java.util.Observable;
import java.util.Observer;
import java.util.StringTokenizer;

public class TaxStudent implements Observer {

	/**
	 * Constanta pentru anuntarea esecului inregistrarii unui student la un
	 * curs.
	 */
	public static final String REGISTRATION_FAILED = "registation_failed";

	/**
	 * Referinta catre BD.
	 */
	private DataBase dataBase;

	/**
	 * Studentul curent.
	 */
	private Student objStudent;

	/**
	 * Constructs a student tax component. A new student tax component
	 * subscribes to EV_REGISTER_STUDENT and EV_STUDENT_REGISTRATION_FAIL
	 * events.
	 */
	public TaxStudent(DataBase objDataBase) {
		this.dataBase = objDataBase;
		// Subscribe to EV_REGISTER_STUDENT and EV_STUDENT_REGISTRATION_FAIL
		EventBus.subscribeTo(EventBus.EV_REGISTER_STUDENT, this);
		EventBus.subscribeTo(EventBus.EV_STUDENT_REGISTRATION_FAIL, this);
	}

	/**
	 * Event handler of this student tax component. On receiving a
	 * EV_REGISTER_STUDENT event the student money balance is decremented. If
	 * the EV_STUDENT_REGISTRATION_FAIL event is received, then the balance is
	 * incremented.
	 * 
	 * @param event
	 *            an event object. (caution: not to be directly referenced)
	 * @param param
	 *            a parameter object of the event. (to be cast to appropriate
	 *            data type)
	 */
	public void update(Observable event, Object param) {
		StringTokenizer objTokenizer1 = new StringTokenizer((String) param);

		String param1 = objTokenizer1.nextToken();

		if (param1.compareTo(TaxStudent.REGISTRATION_FAILED) == 0) {
			if (objStudent != null) {

				// Studentul primeste banii inapoi.
				objStudent.iBalance++;
				EventBus.announce(EventBus.EV_SHOW, "Studentul " + objStudent.getName() + " a primit banii inapoi.");
			}
		} else {

			// Obtinerea referintei catre student.
			StringTokenizer objTokenizer = new StringTokenizer(((String) param).substring(2));
			String sSID = objTokenizer.nextToken();
			objStudent = this.dataBase.getStudentRecord(sSID);

			if (objStudent != null) {

				// Taxarea studentului.
				objStudent.iBalance--;
				EventBus.announce(EventBus.EV_SHOW, "Studentul " + objStudent.getName() + " a fost taxat.");
			}

		}
	}

}